<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElNotification } from 'element-plus';
import HeaderDemo from '../components/HeaderDemo.vue';
import FooterComp from '../components/FooterComp.vue';

// 获取路由参数
const route = useRoute();
const submissionId = ref(route.params.id); // 获取传递的 id


// 存储详情页的数据
const submissionDetails = ref({});

// 存储可用的剧本列表
const availableScripts = ref([]);

// 所有可能的剧本名称列表
const allScripts = [
  { id: 1, title: '《流浪的星球》' },
  { id: 2, title: '《时光之钥》' },
  { id: 3, title: '《梦中的王国》' },
  { id: 4, title: '《海边的秘密》' },
  { id: 5, title: '《沙漠之歌》' },
  { id: 6, title: '《永恒的火焰》' },
  { id: 7, title: '《森林之灵》' },
  { id: 8, title: '《冰封的传说》' },
  { id: 9, title: '《未知的旅程》' },
  { id: 10, title: '《黑夜的咏叹调》' }
];

// 随机生成 6 个剧本名字
const generateRandomScripts = () => {
  const selectedScripts = new Set();
  while (selectedScripts.size < 6) {
    const randomIndex = Math.floor(Math.random() * allScripts.length);
    selectedScripts.add(allScripts[randomIndex]);
  }
  availableScripts.value = Array.from(selectedScripts);
};

// 获取所有数据并筛选出特定 id 的数据
const fetchAllSubmissions = async () => {
  try {
    const response = await axios.get('http://localhost:8080/submissions/all');
    console.log('所有投稿数据:', response.data);
    console.log('当前 id:', submissionId.value);
    
    const detail = response.data.find(item => item.id === parseInt(submissionId.value));
    if (detail) {
      submissionDetails.value = detail;
      console.log('找到的详情数据:', submissionDetails.value);
    } else {
      console.error('未找到匹配的详情数据');
    }
  } catch (error) {
    console.error('获取投稿数据失败:', error);
  }
};

// 在页面加载时调用获取详情数据的函数
onMounted(() => {
  console.log("页面加载："+submissionId.value);
  
  if (submissionId.value) {
    fetchAllSubmissions();
  }
});

// 控制弹窗的状态
const dialogVisible = ref(false);
const formData = ref({
  name: '',
  contact: '',
  fileList: [],
  script: null
});

// 打开弹窗的函数
const handleOpen = () => {
  dialogVisible.value = true;
  console.log('投稿按钮被点击了' + dialogVisible.value);
};

// 提交表单的函数，提交后弹出“投稿成功！”的通知
const handleSubmit = () => {
  console.log('Submitting Form Data:', formData.value);
  if (formData.value.name && formData.value.contact && formData.value.script) {
    ElNotification({
      title: '成功',
      message: '投稿成功！',
      type: 'success',
      duration: 2000
    });
    console.log('Form submitted successfully!');
    dialogVisible.value = false;
  } else {
    console.error('Please fill in all fields, select a script and upload a file!');
  }
};

// 关闭弹窗的函数
const handleClose = () => {
  console.log('Dialog closed');
  dialogVisible.value = false;
  formData.value = { name: '', contact: '', fileList: [], script: null };
};

// 计算属性，格式化 submissionDetails.fileName，将换行符替换为 <br>
const formattedFileName = computed(() => {
  return submissionDetails.value.fileName ? submissionDetails.value.fileName.replace(/\n/g, '<br>') : '';
});
</script>



<template>
  <el-header class="header">
    <HeaderDemo />
  </el-header>
  <div class="container">
    <div class="script-container">
      <div class="title-container">
        <span class="for-sale">【{{ submissionDetails.category }}】</span>
        <span class="title">{{ submissionDetails.title }}</span>
      </div>
      <div class="meta-info">
        <span>{{ submissionDetails.publishDate }}</span>
        <span>发布：{{ submissionDetails.publisher }}</span>
        <hr/>
      </div>
      <div class="content">
        <!-- 使用 v-html 来显示带有换行的内容 -->
        <p v-html="formattedFileName"></p>
        <p>联系方式：<a href="#">点击查看</a></p>
        
        <el-button type="primary" @click="handleOpen">投稿</el-button>
      </div>
    </div>
    <FooterComp />
  </div>
  <!-- 弹窗 -->
  <el-dialog title="投稿" v-model="dialogVisible" @close="handleClose">
    <el-form :model="formData" label-width="100px">
      <el-form-item label="姓名">
        <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input v-model="formData.contact" placeholder="请输入联系方式"></el-input>
      </el-form-item>
      <!-- 新增 "选择剧本" 的下拉框 -->
      <el-form-item label="选择剧本">
        <el-select v-model="formData.script" placeholder="请选择剧本" @focus="generateRandomScripts">
          <el-option
            v-for="(script, index) in availableScripts"
            :key="index"
            :label="script.title"
            :value="script.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>


<style scoped>
.header{
  height: 80px;
  background-color: black;
}
html, body {
  height: 100%;
  margin: 0;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 确保内容上下分开 */
  background-color: #f0f0f0; /* 背景浅灰色 */
  min-height: 100vh; /* 确保最小高度为100vh */
  /* 子元素居中 */
  align-items: center;
}

.script-container {
  width: 80%;
  min-height: 500px;
  background-color: #ffffff;
  padding: 20px;
  border: 1px solid #eaeaea;
  font-family: Arial, sans-serif;
  margin-top: 100px;
  margin-bottom: 130px;
}

.title-container {
  display: flex;
  align-items: baseline;
  margin-bottom: 10px;
}

.for-sale {
  color: red;
  font-weight: bold;
  margin-right: 8px;
}

.title {
  font-size: 24px;
  font-weight: bold;
}

.meta-info {
  font-size: 12px;
  color: #888;
  margin-bottom: 15px;
}

.content p {
  font-size: 18px;
  line-height: 1.6;
  color: #333;
  margin: 10px 0;
}

.content a {
  color: #007bff;
  text-decoration: none;
}

.content a:hover {
  text-decoration: underline;
}

.footer {
  margin-top: auto; /* 让footer自动填充空间 */
}
</style>
